<?php

namespace app\lib\exception;

use app\lib\exception\BaseException;
use think\exception\Handle;
use think\Request;
use think\log;
//继承TP5全局处理
//定义全局处理样式
class ExceptionHandler extends Handle
{
    //定义
    private $code;
    private $msg;
    private $errorCode;
    //需要返回Url路径

    public function render(\Exception $e)
    {
        //判断错误信息属于那一类

        //1.客户端的异常信息处理（自定义异常：不符合验证规则）
        if ($e instanceof BaseException) {
            # code...
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }
        //2.服务端异常处理
        else {
            if (config('app_debug')) {
                # code...
                return parent::render($e);
            } else {
                # code...
                $this->code = 500;
                $this->msg = '扑街仔的烂代码，点解、母鸡';
                $this->errorCode = 999;
                $this->recordErrorLog($e);
            }
        }

        $request = Request::instance();
        //返回结果
        $result = [
            'msg' => $this->msg,
            'errorCode' => $this->errorCode,
            'request_url' => $request->url()
        ];
        return json($result, $this->code);
    }

    //自定义储存日志
    private function recordErrorLog(\Exception $e)
    {
        //初始化日志
        log::init([
            // 日志记录方式，内置 file socket 支持扩展
            'type'  => 'File',
            // 日志保存目录
            'path'  => LOG_PATH,
            // 日志记录级别
            'level' => ['error'],
        ]);
        Log::record($e->getMessage(), 'error');
    }
}
